package com.atguigu.guli.infrastructure.apigateway.filter;

import com.atguigu.guli.service.base.helper.JwtHelper;
import com.atguigu.guli.service.base.result.ResultCodeEnum;
import com.google.gson.JsonObject;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.nio.charset.StandardCharsets;
import java.util.List;

@Component
@Slf4j
public class AuthGlobalFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        log.info("执行网关全局过滤");

        //取出请求路径，检查请求路径中是否存在/auth/，如果存在则鉴权，如果不存在则放行
        ServerHttpRequest request = exchange.getRequest();
        String path = request.getURI().getPath();
        log.info("path =" + path);

        //检查请求路径中是否存在/auth/
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        if (antPathMatcher.match("/api/**/auth/**", path)){
            //存在
            log.info("需要鉴权");
            //取出token
            List<String> tokenList = request.getHeaders().get("token");

            //没有token,输出错误响应
            if (tokenList == null){
                ServerHttpResponse response = exchange.getResponse();
                //返回统一的异常响应结果
                return out(response);
            }

            //token校验失败
            boolean isOk = JwtHelper.checkToken(tokenList.get(0));
            if (!isOk){
                ServerHttpResponse response = exchange.getResponse();
                //返回统一的异常响应结果
                return out(response);
            }

            //跳转到登录页面(前端实现)

        }

        //放行
        return chain.filter(exchange);
    }

    //定义当前过滤器的优先级，值越小，优先级越高
    @Override
    public int getOrder() {
        return 0;
    }

    private Mono<Void> out(ServerHttpResponse response) {
        JsonObject message = new JsonObject();
        message.addProperty("success", ResultCodeEnum.LOGIN_AUTH.getSuccess());
        message.addProperty("code", ResultCodeEnum.LOGIN_AUTH.getCode());
        message.addProperty("data", "");
        message.addProperty("message", ResultCodeEnum.LOGIN_AUTH.getMessage());
        byte[] bytes = message.toString().getBytes(StandardCharsets.UTF_8);
        DataBuffer buffer = response.bufferFactory().wrap(bytes);
        //指定编码，否则在浏览器中会中文乱码
        response.getHeaders().add("Content-Type", "application/json;charset=UTF-8");
        //输出http响应
        return response.writeWith(Mono.just(buffer));

    }
}
